<template>
  <el-card>
    <el-row :gutter="10">
      <el-col :span="6">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-col>
      <el-col :span="6">
        <el-select placeholder="请选择订单状态" v-model="formData.status">
          <el-option label="全部" :value="1"></el-option>
          <el-option label="进行中" :value="2"></el-option>
          <el-option label="已完成" :value="3"></el-option>
          <el-option label="异常" :value="4"></el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-input placeholder="请输入设备编号" v-model="formData.no" />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="loadData">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
      <el-col :span="6" class="mt">
        <el-input placeholder="请输入站点名称" v-model="formData.name" />
      </el-col>
      <el-col :span="6" class="mt">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="/"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="handleChange"
          value-format="YYYY-MM-DD"
        />
      </el-col>
    </el-row>
  </el-card>
  <el-card class="mt">
    <el-button
      type="primary"
      :disabled="!selectionList.length"
      @click="handleBatchDelete"
      >批量删除</el-button
    >
    <el-button icon="Download" type="danger" :disabled="!selectionList.length"
    @click="exportExcel"
      >导出订单数据到EXCEL</el-button
    >
  </el-card>
  <el-card class="mt">
    <el-table
      :data="dataList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="80"></el-table-column>
      <el-table-column label="订单号" prop="orderNo"></el-table-column>
      <el-table-column label="设备编号" prop="equipmentNo"></el-table-column>
      <el-table-column label="订单日期" prop="date"></el-table-column>
      <el-table-column label="开始时间" prop="startTime"></el-table-column>
      <el-table-column label="结束时间" prop="endTime"></el-table-column>
      <el-table-column label="金额" prop="money"></el-table-column>
      <el-table-column label="支付方式" prop="pay"></el-table-column>
      <el-table-column label="订单状态" prop="status">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 2">进行中</el-tag>
          <el-tag type="primary" v-if="scope.row.status === 3">已完成</el-tag>
          <el-tag type="warning" v-if="scope.row.status === 4">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="status" width="150px">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleDetail(scope.row.orderNo)"
            >详情</el-button
          >
          <el-button type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt mb fr"
      background
      v-model:current-page="pageInfo.page"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totals"
      @size-change="handleSizechange"
      @current-change="handlePageNochange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useHttp } from '@/hooks/useHttp';
import { batchDelete } from '@/api/operations';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useTabsStore } from '@/store/tabs';
import * as XLSX from "xlsx";
import {saveAs} from "file-saver"
const router = useRouter();
const route = useRoute();

const { addTab, setCurrentTab } = useTabsStore();
interface SearchParams {
  orderNo: string;
  status: number;
  no: string;
  name: string;
  startDate: string;
  endDate: string;
}

interface SelectionListType {
  orderNo: string;
  equipmentNo: string;
  date: string;
  startDate: string;
  endDate: string;
  money: string;
  pay: string;
  status: number;
}
const date = ref([]);
const formData = ref<SearchParams>({
  orderNo: '',
  status: 1,
  no: '',
  name: '',
  startDate: '',
  endDate: '',
});
const handleChange = (e: string[]) => {
  formData.value.startDate = e[0];
  formData.value.endDate = e[1];
};

const {
  dataList,
  loading,
  totals,
  pageInfo,
  loadData,
  handleSizechange,
  handlePageNochange,
  resetPagination,
} = useHttp<SelectionListType>('/orderList', formData); // 不能.value ,传过去的formData得是响应式数据

const handleReset = () => {
  date.value = [];
  formData.value = {
    orderNo: '',
    status: 1,
    no: '',
    name: '',
    startDate: '',
    endDate: '',
  };
  resetPagination();
};
const selectionList = ref<SelectionListType[]>([]);
const handleSelectionChange = (value: SelectionListType[]) => {
  selectionList.value = value;
};

const handleBatchDelete = async () => {
  try {
    const res = await batchDelete(
      selectionList.value.map((item: SelectionListType) => item.orderNo)
    );
    if (res.code === 200) {
      ElMessage({
        message: res.data,
        type: 'success',
      });

      loadData();
    }
  } catch (error) {
    console.log('👿 ~ handleBatchDelete ~ error:', error);
  }
};

const handleDetail = (orderNo: string) => {
  addTab('订单详情', '/operations/Detail', 'Share');
  setCurrentTab('订单详情', '/operations/Detail');
  router.push({
    path: '/operations/Detail',
    query: {
      orderNo,
    },
  });
};

watch(
  () => route.name,
  (to, from) => {
    console.log('👿 ~ watch ~ to:', to, from);

    if (to === 'orders' && from !== 'detail') {
      loadData();
    }
  }
);

const exportExcel = ()=>{
    const ws = XLSX.utils.json_to_sheet(selectionList.value); //把数据转化成工作表格式
    const wb = XLSX.utils.book_new(); //创建工作簿
    XLSX.utils.book_append_sheet(wb, ws, '表1'); //把工作表添加到工作簿
    const wbout = XLSX.write(wb,{ // 输出格式
        bookType:'xlsx',
        type:"array"
    })
    const blob =  new Blob([wbout],{type:'application/octet-stream'})
    saveAs(blob,'订单数据.xlsx')
}
</script>
